package net.xdclass.service.impl;

import net.xdclass.service.CustomRulesService;
import net.xdclass.service.GoogleSafeBrowsingService;
import net.xdclass.service.MachineLearningService;
import net.xdclass.service.LinkSafetyService;
import net.xdclass.util.JsonData;
import net.xdclass.util.JsonUtil;
import net.xdclass.vo.LinkSafetyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
@EnableAsync
public class LinkSafetyServiceImpl implements LinkSafetyService {

    private static final String CACHE_KEY_PREFIX = "url:safety:";

    @Autowired
    private GoogleSafeBrowsingService googleSafeBrowsingService;

    @Autowired
    private CustomRulesService customRulesService;

    @Autowired
    private MachineLearningService machineLearningService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public LinkSafetyVO checkLink(String url) throws ExecutionException, InterruptedException {
        // 从 Redis 缓存中获取结果
        String cachedResult = redisTemplate.opsForValue().get(CACHE_KEY_PREFIX + url);
        if (cachedResult != null) {
            return JsonUtil.json2Obj(cachedResult, LinkSafetyVO.class);
        }

        // 异步调用检测服务
        CompletableFuture<Boolean> googleSafeFuture = googleSafeBrowsingService.detect(url);
        CompletableFuture<Boolean> customRulesFuture = customRulesService.detect(url);
        CompletableFuture<Boolean> machineLearningFuture = machineLearningService.detectMac(url);

        // 等待所有异步任务完成
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(googleSafeFuture, customRulesFuture, machineLearningFuture);

        // 计算权重分数
        allFutures.join();
        int googleSafeScore = googleSafeFuture.get() ? 50 : 0;
        int customRulesScore = customRulesFuture.get() ? 25 : 0;
        int machineLearningScore = machineLearningFuture.get() ? 25 : 0;

        int totalScore = googleSafeScore + customRulesScore + machineLearningScore;

        // 综合判断
        boolean isSafe = totalScore >= 75; // 假设总分100分为安全
        String message = isSafe ? "安全链接" : "恶意链接";
        String details = String.format("Google Safe Browsing: %s, 自定义规则: %s, 机器学习模型: %s",
                googleSafeScore == 50 ? "安全" : "恶意",
                customRulesScore == 25 ? "安全" : "恶意",
                machineLearningScore == 25 ? "安全" : "恶意"
        );

        // 缓存结果
        LinkSafetyVO resultVO = new LinkSafetyVO(isSafe, message, details);
        redisTemplate.opsForValue().set(CACHE_KEY_PREFIX + url, JsonUtil.obj2Json(resultVO), 10, TimeUnit.HOURS);

        return resultVO;
    }
}
